﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.Common;
using DHQGHN.DAL.Common;
using DHQGHN.PM0.Models.Admin;
using DHQGHN.PM0.Controllers;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.MVC.Controllers;

namespace DHQGHN.PM0.Controllers.Admin
{
    public class UserInRoleController : BaseController
    {
        UserInRoleBO userInRoleBO;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(UserInRoleController));

        private IEnumerable<SelectListItem> getListApp()
        {
            try
            {
                ApplicationBO appBO = new ApplicationBO();
                var lstApp = appBO.GetAll();
                List<SelectListItem> lstItems = new List<SelectListItem>();
                lstItems.Add(new SelectListItem
                {
                    Value = "0",
                    Text = "Chọn ứng dụng"
                });
                foreach (var type in lstApp)
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = type.AppId.ToString(),
                        Text = type.AppName
                    });
                }

                return new SelectList(lstItems, "Value", "Text");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        private IEnumerable<SelectListItem> getListRoleByAppID(int? appId)
        {
            try
            {
                RoleBO roleBO = new RoleBO();
                var lstRole = roleBO.GetAllByAppId(appId.Value);
                List<SelectListItem> lstItems = new List<SelectListItem>();
                lstItems.Add(new SelectListItem
                {
                    Value = "0",
                    Text = "Chọn vai trò"
                });
                foreach (var type in lstRole)
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = type.RoleId.ToString(),
                        Text = type.RoleName
                    });
                }

                return new SelectList(lstItems, "Value", "Text");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        public ActionResult Index(UserInRoleModel m = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", int currentId = -1)
        {
            try
            {
                SetActiveMenu("/UserInRole/Index");
                if (m== null) m= new UserInRoleModel();
                m.RoleID = 0;
                var model = search(m, pageIndex, currentId, false);
                ViewBag.lstRole = getListRole();
                ViewBag.lstApp = CommonData.getListApp();
                return View("~/Views/UserInRole/UserInRole.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Action lay danh sach role by Appid dang Json
        /// </summary>
        /// <param name="appId"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetListRoleByID(int appId)
        {
            try
            {
                var roles = getListRoleByAppID(appId);
                return Json(roles, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// Hiển thị form thêm mới người dùng
        [HttpPost]
        public ActionResult actionPrepareCreateOrUpdateUserInRole(int? id, int roleID, int appid)
        {
            try
            {
                ViewBag.AppID = appid;
                ViewBag.lstApp = CommonData.getListApp();
                UserInRoleModel model = null;
                if (roleID > -1)
                {
                    if (id != null && id > -1)
                    {
                        userInRoleBO = new UserInRoleBO();
                        model = new UserInRoleModel(userInRoleBO.GetUserInRoleById(id));
                    }
                    if (model == null)
                    {
                        model = new UserInRoleModel()
                        {
                            UserInRoleID = -1,
                            UserID = -1,
                            RoleID = roleID,
                            Descriptions = "",
                            IsActive = 1
                        };
                    }
                    ViewBag.lstRole = getListRole();
                    ViewBag.lstUser = getListActiveUser(getListUser(appid), getListUserInRoleByRoleID(roleID));
                    if (Request.IsAjaxRequest())
                    {
                        return PartialView("~/Views/UserInRole/_UserInRoleModel.cshtml", model);
                    }
                }
                return View(model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        public ActionResult actionSearch(UserInRoleModel aModel = null, int pageIndex = 0, string sort = "UserInRoleId", string sortDir = "ASC", int currentId = -1)
        {
            try
            {
                if (aModel == null) aModel = new UserInRoleModel();
                
                if (aModel.RoleID == -1)
                    aModel.RoleID = 0;

                var model = search(aModel, pageIndex, currentId, false);
                ViewBag.lstRole = getListRole();
                ViewBag.roleID = aModel.RoleID.ToString();
                return PartialView("~/Views/UserInRole/_UserInRoleList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// Thêm mới người dùng
        [HttpPost]
        [ValidateInput(false)]
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionCreateOrUpdateUserInRole(UserInRoleModel model, int[] listID)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    userInRoleBO = new UserInRoleBO();
                    bool result = userInRoleBO.createOrUpdateUserInRole(model.toDALModel(), listID);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            LogStream.GetJsonString<UserInRoleModel>(model) +
                            CommonData.GetListId("Danh sách UserId: ", ";", listID),
                            Resources.Localization.ActionSaveUpdateCaption + " - actionCreateOrUpdateUserInRole");

                        if (model.UserInRoleID > -1)
                        {
                            return Json(JsonResponse.Json200("Cập nhật vai trò người dùng thành công!"));
                        }
                        else
                        {
                            return Json(JsonResponse.Json200("Gán vai trò cho người dùng thành công!"));
                        }
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }

                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        [AjaxValidateAntiForgeryToken]
        public ActionResult actionDelete(int[] id)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    userInRoleBO = new UserInRoleBO();
                    bool result = userInRoleBO.deleteUserInRole(id);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId("Danh sách UserInRoleId: ", ";", id),
                            Resources.Localization.ActionDeleteCaption + " - actionDelete");

                        return Json(JsonResponse.Json200("Xóa người dùng thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        private DataPage<UserInRoleModel> search(UserInRoleModel myModel, int pageIndex, int currentId, bool compareEqual)
        {
            try
            {
                userInRoleBO = new UserInRoleBO();
                var models = new DataPage<UserInRoleModel>();
                var DALModel = userInRoleBO.GetDynamicListPaging(myModel.toDALModel(), PageSize, pageIndex, compareEqual);
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.UserInRoleModel gender in lstItem)
                {
                    models.Data.Add(new UserInRoleModel(gender));
                }

                UserInRoleModel model = null;
                if (currentId >= 0 && models.Data.Count > 0)
                {
                    model = models.Data.Find(user => user.UserInRoleID == currentId);
                    models.CustomData = model;
                }
                else
                {
                    models.CustomData = myModel;
                }
                if (models.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "UserInRole",
                        CurrentPage = pageIndex,
                        InputSearchId = "",
                        TagetReLoadId = "user-in-role-list",

                    };
                    pagNative.TotalRows = models.Data[0].RecordCount;
                    pagNative.CurrentRow = models.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return models;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<SelectListItem> getListRole()
        {
            try
            {
                RoleBO roleBO = new RoleBO();
                var lstType = roleBO.GetAll();
                List<SelectListItem> lstItems = new List<SelectListItem>();
                lstItems.Add(new SelectListItem
                {
                    Value = "-1",
                    Text = "Chọn vai trò"
                });
                foreach (var type in lstType)
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = type.RoleId.ToString(),
                        Text = type.RoleName
                    });
                }

                return new SelectList(lstItems, "Value", "Text");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        //Get all user in a role of database
        private Dictionary<int, int> getListUserInRoleByRoleID(int roleID)
        {
            try
            {
                userInRoleBO = new UserInRoleBO();
                Dictionary<int, int> lstMenu = new Dictionary<int, int>();
                var lstItems = userInRoleBO.GetListUserInRoleByRoleID(roleID);
                foreach (var user in lstItems)
                {
                    if (!lstMenu.ContainsKey(user.UserID))
                    {
                        lstMenu.Add(user.UserID, user.RoleID);
                    }
                }
                return lstMenu;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private List<UserModel> getListUser(int? AppId)
        {
            try
            {
                UserBO userBO = new UserBO();
                var lstUser = userBO.GetAll(AppId);
                List<UserModel> lstItems = new List<UserModel>();
                foreach (var user in lstUser)
                {
                    lstItems.Add(new UserModel(user));
                }
                return lstItems;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<SelectListItem> getListActiveUser(List<UserModel> lstUser, Dictionary<int, int> lstUserInRole)
        {
            try
            {
                List<SelectListItem> lstItems = new List<SelectListItem>();
                foreach (var user in lstUser)
                {
                    if (!lstUserInRole.ContainsKey(user.ID))
                    {
                        lstItems.Add(new SelectListItem
                        {
                            Value = user.ID.ToString(),
                            Text = user.UserName
                        });
                    }
                }
                return new SelectList(lstItems, "Value", "Text");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private string GetFunction()
        {
            return "Phân vai trò cho người dùng - UserInRole";
        }
    }
}